from mako.template import Template
import gen_view_info

def main(para):
    if 'viewnum' not in para:
        para['viewnum'] = 0
    if 'viewprefix' not in para:
        para['viewprefix'] = 'view'
    if 'client' not in para:
        para['client'] = '127.0.0.1'
    if para['client'] == 'None':
        para['client'] = '127.0.0.1'
        
    viewlist = gen_view_info.gen_rand_view(para['viewnum'], para['viewprefix'])
    nomatch_aclrule = []
    match_aclrule = []
    if para['client'] != '127.0.0.1':
        ipinfo = para['client'].split('.')      
        for i in range(128):
           for j in range(2):
              if i != int(ipinfo[3]):
                 nomatch_aclrule.append({'ip':str(i) + '.' + ipinfo[1] + '.' + str(j) + '.0', 'mask':24})
              match_aclrule.append({'ip':ipinfo[0] + '.' + str(i) + '.' + str(j) + '.0', 'mask':24})
        match_aclrule.append({'ip':para['client'], 'mask':32})
    for view in viewlist:
        if viewlist.index(view) == len(viewlist) -1 :
             gen_acl(match_aclrule, para['aclpath'] + "/" + view + "_acl.xml")
        else:
             gen_acl(nomatch_aclrule, para['aclpath'] + "/" + view + "_acl.xml")
         
def gen_acl(rule_list, outfile):
    makotext = '''
<access_control>
    <network ip = \"127.0.0.1\" mask = \"32\" />
% for net in rule_list:
    <network ip = \"${net["ip"]}\" mask = \"${net["mask"]}\" />
% endfor
</access_control>

'''
    tpl = Template(makotext)
    txt = tpl.render(rule_list = rule_list)
    with open(outfile, 'w') as fp:
       fp.write(txt)

if __name__ == "__main__":
    #net1 = {"ip":"127.0.0.1", "mask":"24"}
    #net2 = {"ip":"203.119.80.0", "mask":"24"}
    #gen_acl([net1,net2])
    #gen_acl([])
    opts = {}
    opts['viewnum'] = 2 
    opts['client'] = '202.173.9.16'
    opts['aclpath'] = 'temp'
    main(opts)
